package dyyx.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;

public abstract class CommUtil {
	
	private static final String UTF8 = "utf8";

	
	
	public static String readFromResource(String name,String charset) throws Exception {
		byte[] bytes = readBytesFromResource(name);
		if(bytes==null || bytes.length<=0){
			return null;
		}
		if(StringUtils.isBlank(charset)){
			charset = UTF8;
		}
		return new String(bytes);
	}

	
	public static byte[] readBytesFromResource(String name) throws Exception {
		InputStream is = null;
		try {
			is = CommUtil.class.getResourceAsStream(name);
			
			//is = CommUtil.class.getClassLoader().getResourceAsStream(name);
			
			if(is==null){
				is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
			}
			
			if (is == null) {
				throw new Exception("resource not find,name=" + name);
			}
			return toBytes(is);
		} finally {
			close(is);
		}
	}
	
	
	   private static byte[] toBytes(InputStream is)throws Exception{
	    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	    	int tmp = 0;
	    	while((tmp=is.read())!=-1){
	    		bos.write(tmp);
	    	}
	    	return bos.toByteArray();
	    }

	    public static void close(Closeable obj) {
			if (obj == null) {
				return;
			}
			try {
				obj.close();
			} catch (Throwable e) {

			}
		}
	    
	    

	
}
